package com.qingke.example;

import java.io.IOException;
import java.sql.Connection;
import java.util.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qingke.pojo.User;


/**
 * Servlet implementation class SendMessageServlet
 */
@WebServlet("/SendMessageServlet")
public class SendMessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private final String driver="com.mysql.jdbc.Driver";
	private final String url="jdbc:mysql://localhost:3306/web?useSSL=false";
	private final String u="root";
	private final String p="6775";

	private Connection conn = null;
	private String sql;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
       
    public SendMessageServlet() {
        super();
    }
    
	public void init(ServletConfig config) throws ServletException {
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, u, p);
			System.out.println("Connect to database successfully!");
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}


	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		List<String> msgs=(List<String>)request.getServletContext().getAttribute("chat");
		if(msgs==null){
			msgs=new ArrayList<String>();
		}
		String username=(String)request.getSession().getAttribute("username");
		String name=getUserByUsername(username).getName();
		Date date= new Date();
		
		String msg=request.getParameter("message");
		insertMessage(name, msg, date.getTime());
		System.out.println("send success");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		
		String message=name+":"+msg+" "+sdf.format(date);
		if(message!=null&&!message.trim().equals("")){
			msgs.add(message);
		}
		request.getServletContext().setAttribute("chat", msgs);
		response.getWriter().append("success");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private void insertMessage(String name,String msg,long date){
		sql="insert into message(name,message,time) values(?,?,?)";
		
		try {
			ps=conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, msg);
			ps.setTimestamp(3,new java.sql.Timestamp(date));
			int count=ps.executeUpdate();
			if(count>0)
				System.out.println("insert success.");
			else
				System.out.println("insert failed.");
				
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	private User getUserByUsername(String username){
    	sql="select * from user where username=?";
    	User user=null;
    	try {
			ps=
					conn
					.prepareStatement(sql);
		    ps.setString(1,username);
		    rs=ps.executeQuery();
		    if(rs.next()){
		    	user=new User();
		    	user.setId(rs.getInt("id"));
		    	user.setUsername(rs.getString("username"));
		    	user.setPassword(rs.getString("password"));
		    	user.setName(rs.getString("name"));
		    }
		    return user;
		    
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	return user;
    }
	public static void main(String[] args){
		Date date=new Date(System.currentTimeMillis());
		System.out.println(date);
	}
}
